# -*- coding: utf-8 -*-
#
# fusion.feed.processmedia
#
# Copyright 2007 Helsinki Institute for Information Technology
# and the authors.
#
# Authors: Harri Hämäläinen <harri.hamalainen@helsinki.fi>
#

# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

# This script tries to generate feed entries for directly imported media files.
# However, we should not import big media files into fusion db as it is not the main intrest of us 
#
# XXX: Currently only owner of the collection is allowed to import media directly into /media
#       Friends (if allowed) can upload content into /file with Value.py
#       It might be nice to allow also friends import media with POST into /media,
#       but now it's better to wait possible changes for our fingerprint policy

from binascii import b2a_hex as bytes_to_hex
from datetime import datetime
from simplejson import dumps

def process_imported_media(db, collection):
    my_identity = bytes_to_hex(db.get_default_identity().get_fingerprint())
    mediafiles = db.keys(collection, key_prefix='media')
    feed_keys = db.keys(collection, key_prefix='feed/entries')
    feed_data = []
    entries_to_generate = []

    for i in range(len(feed_keys)):
        # append([filename, filename/fingerprint])
        feed_data.append([feed_keys[i].split('/')[0], feed_keys[i]])

    for mediafile in mediafiles:
        entry_is_empty = True
        for entryname in feed_data:
            if mediafile == entryname[0] \
                    and db.get(collection, 'media/'+entryname[0]) != '':
                if db.get(collection,'feed/entries/'+entryname[1]):
                    entry_is_empty = False
        if entry_is_empty:
            entries_to_generate.append(mediafile)

    for i in range(len(entries_to_generate)):
        entry = {
            'published': datetime.today().isoformat(),
            'title': entries_to_generate[i],
            'author': {
                'name': db.get_local_info('default_profile'),
                'name': db.get(db.get_local_info('default_profile'), 'info/title')
            },
            'content': entries_to_generate[i],
            'link': [{
                'rel': 'enclosure',
                'href': '/collection/'+collection+'/media/'+entries_to_generate[i]
            }]
        }
        db.post(collection, 'feed/entries/'+entries_to_generate[i], dumps(entry))
     

if __name__ == '__main__':
    from fusion.db.db import DB
    db = DB("~/.fusion/fusion.db")
    process_imported_media(db, "aa77744761d60cad0672ee81d4035efc3d6db2d4")
    db.close()
